package com.example.download;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

public class SplitedFile {
    private RandomAccessFile mFile;
    private static final int PER_BYTES_SIZE = 1024 * 100;

    private SplitedFile() {

    }

    SplitedFile(File file) throws FileNotFoundException {
        super();
        mFile = new RandomAccessFile(file, "rw");
    }

    SplitedFile(String filePath) throws FileNotFoundException {
        super();
        mFile = new RandomAccessFile(filePath, "rw");
    }

    /**
     * 重传时调用
     *
     * @param startOff
     * @return 返回SplitedBytes.length==-1或者<PER_BYTES_SIZE时，说明文件到头
     */
    public SplitedBytes getBytes(long startOff) {
        SplitedBytes splitedBytes = new SplitedBytes();
        try {
            mFile.seek(startOff);
            splitedBytes.length = mFile.read(splitedBytes.bytes);

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return splitedBytes;
    }

    public class SplitedBytes {
        SplitedBytes() {
            bytes = new byte[PER_BYTES_SIZE];
            length = -1;
        }

        public byte[] bytes;
        public int length;
    }

    /**
     * @return -1 说明错误
     */
    public long getFileLength() {
        long length = -1;
        try {
            length = mFile.length();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return length;
    }

    public void setFileLength(long length) {
        try {
            mFile.setLength(length);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 不加锁应该也没事，以防万一
    synchronized public boolean writeFile(long startOff, byte[] bytes) {
        boolean result = false;
        if (bytes.length != -1) {
            try {
                mFile.seek(startOff);
                mFile.write(bytes, 0, bytes.length);
                result = true;
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return result;
    }

    public void close() {
        try {
            mFile.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
